#include <gtk/gtk.h>
#include <cairo/cairo.h>
#include <time.h>

#include "common.h"

static char buffer[256];

static gboolean on_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data);
static gboolean time_handler(GtkWidget *widget);

int main( int argc, char *argv[]){
    GtkWidget *window;
    GtkWidget *drawingArea;

    gtk_init(&argc, &argv);

    /* window */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    gtk_widget_set_size_request (window, 300, 250);         /*设置窗口大小*/
    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);    /*设置窗口不能拉伸*/
    gtk_window_set_title(GTK_WINDOW(window), TITLE);
    gtk_container_set_border_width(GTK_CONTAINER(window), 15);  /*设置容器边界大小*/

    /* drawingArea */
    drawingArea = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(window), drawingArea);
    g_signal_connect(GTK_OBJECT(drawingArea), "expose-event", G_CALLBACK(on_expose_event), NULL);

    /* timer */
    g_timeout_add(1000, (GSourceFunc)time_handler, (gpointer)window);
    time_handler(window);

    g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_widget_show_all(window);
    gtk_main();

    return 0;
}

static gboolean on_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data)
{
    cairo_t *cr;

    cr = gdk_cairo_create(widget->window);

    cairo_move_to(cr, 30, 30);
    cairo_show_text(cr, buffer);

    cairo_destroy(cr);
    return FALSE;
}

static gboolean time_handler(GtkWidget *widget)
{
    if (widget->window == NULL) {
        return FALSE;
    }

    time_t curtime;
    struct tm *loctime;
    curtime = time(NULL);
    loctime = localtime(&curtime);
    strftime(buffer, 256, "%T", loctime);
    gtk_widget_queue_draw(widget);
    return TRUE;
}
